package com.itheima.dianming.template;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.dianming.exception.BusinessException;
import com.itheima.dianming.filter.UserHolder;
import com.itheima.dianming.pojo.domain.ModelInterface;
import com.itheima.dianming.pojo.domain.StuInterface;
import com.itheima.dianming.pojo.domain.StuInterfaceTestLog;
import com.itheima.dianming.service.StuInterfaceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class RunTemplate {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${dingding.ruiji.path}")
    private String path;

    @Autowired
    private StuInterfaceService stuInterfaceService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${dingding.ruiji.logqueue}")
    private String queueName;

    public void runModules(Long stuId,Long pid,List<ModelInterface> list) {
        String loginCookie=null;
        try{
            loginCookie = login("http://localhost:8080/employee/login");
        }catch (Exception e){
            e.printStackTrace();
            StuInterfaceTestLog testLog =
                    new StuInterfaceTestLog(null,stuId,pid,5L,"登录出错："+e.getMessage());
            rabbitTemplate.convertAndSend(queueName,testLog);
            throw new BusinessException("登录出错");
        }

        ModelInterface temp =null;
        try{
            for (ModelInterface modelInterface : list) {
                log.info("开始测试接口:{}",modelInterface.getDescription());
                temp = modelInterface;
                runInterface(modelInterface,loginCookie);
            }
        }catch (Exception e){
            e.printStackTrace();
            StuInterfaceTestLog testLog =
                    new StuInterfaceTestLog(null,stuId,pid,5L,"接口测试出错，接口："+temp.getUrl()+",错误信息是："+e.getMessage());
            rabbitTemplate.convertAndSend(queueName,testLog);
            throw new BusinessException("接口测试出错，接口："+temp.getUrl());
        }
    }

    public void runInterface(ModelInterface modelInterface,String loginCookie) {
        String url = modelInterface.getUrl();
        String method = modelInterface.getMethod();
        HttpMethod httpMethod = null;

        if(HttpMethod.GET.matches(method)){
            httpMethod = HttpMethod.GET;
        }
        if(HttpMethod.POST.matches(method)){
            httpMethod = HttpMethod.POST;
        }
        if(HttpMethod.PUT.matches(method)){
            httpMethod = HttpMethod.PUT;
        }
        if(HttpMethod.DELETE.matches(method)){
            httpMethod = HttpMethod.DELETE;
        }
        String param = modelInterface.getParam();
        log.info("开始测试接口，url：{},method:{},param:{}",url,method,param);
        HttpHeaders headers = new HttpHeaders();
        headers.set(HttpHeaders.COOKIE,loginCookie);
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<String>(param,headers);
        ResponseEntity<String> exchange = restTemplate.exchange(path+url.replace(" ",""), httpMethod, entity, String.class);
        HttpStatus statusCode = exchange.getStatusCode();
        String body = exchange.getBody();
        log.info("测试完成，结果是{},数据是{}",statusCode,body);
        LambdaQueryWrapper<StuInterface> qw = new LambdaQueryWrapper<>();
        qw.eq(StuInterface::getStuId, UserHolder.getStuId());
        qw.eq(StuInterface::getProjectId, modelInterface.getProjectId());
        qw.eq(StuInterface::getInterfaceId, modelInterface.getId());
        StuInterface one = stuInterfaceService.getOne(qw);
        if(one!=null){
            one.setResponseCode(statusCode.value());
            one.setIsOk(statusCode.value()==200?1:0);
            one.setIsDown(statusCode.value()==404?0:1);
            one.setCreateTime(new Date());
            one.setDetail("响应码:"+statusCode.value()+",响应内容:"+body);
            stuInterfaceService.updateById(one);
        }
    }

    public String  login(String url) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 设置请求boby
        Map<String, String> body = new HashMap<>();
        body.put("username", "admin");
        body.put("password", "123456");
        HttpEntity<Map<String, String>> entity = new HttpEntity<>(body, headers);
        log.info("开始登录:{},{}",url,body);
        ResponseEntity<String> resp = restTemplate.postForEntity(url, entity, String.class);
        if(resp.getStatusCode().value()!=200){
            throw new BusinessException("登录失败："+resp.getStatusCode()+","+resp.getBody().toString());
        }
        List<String> cookie = resp.getHeaders().get("Set-Cookie");
        log.info("模拟浏览器登录，获取Cookie为：{}", cookie);
        for (String s : cookie) {
            if(s.contains("JSESSIONID")){
                String s1 = s.split(";")[0];
                return s1;
            }
        }
        throw new BusinessException("登录失败");
    }
}
